require 'java'
require 'pathname'

module Init
  EXPECTED_HOME_ENTRIES = ['pom.xml', 'src', 'Gemfile']
  RELATIVE_INIT_PATH = 'src/main/ruby/main/init.rb'

  class << self
    def add_package_shortcuts
      [:de, :eu].each do |meth|
        Kernel.module_eval <<-EOM
          def #{meth}
            JavaUtilities.get_package_module_dot_format('#{meth}')    
          end
        EOM
      end
    end

    def build_maven_loadpath
      project_home_path = Init.project_home_path
      ruby_src_path = File.join(project_home_path, 'src', 'main', 'ruby')
      ruby_test_path = File.join(project_home_path, 'src', 'test', 'ruby')
      [project_home_path, ruby_src_path, ruby_test_path].each do |dir|
        $: << dir unless $:.find_index dir
      end
    end


    def build_maven_classpath
      target_classes = File.join(project_home_path, 'target', 'classes')
      target_test_classes = File.join(project_home_path, 'target', 'test-classes')
      cp_entries = [target_classes, target_test_classes]
      open(File.join(target_classes, 'classpath.list')) do |f|
        cp_string = f.read
        cp_entries += cp_string.split(File::PATH_SEPARATOR)
      end
      cp_entries.each do |entry|
        $CLASSPATH << entry
      end
    end

    def project_home_path
      @project_home ||= begin
        filepath = File.expand_path(__FILE__, '.')

        #Ascend from $PROJECT_ROOT/src/main/ruby/main/init.rb to $PROJECT_ROOT
        Pathname(filepath).ascend { |dir| break dir if maven_home?(dir) }.to_s
      end
    end

    def set_execution_environment
      java_import [de.recipeminer.environments.ExecutionContextProvider,
                   de.recipeminer.environments.ExecutionContext]
      selected_context = ExecutionContextProvider.instance.select_default_context
      puts "Initializing Execution context set to: #{selected_context}"
    end

    def running_in_jar?
      begin
        return Java::DeRecipeminerTools::Tools.executed_from_jar
      rescue NameError
        return nil
      end
    end

    private
    def maven_home?(path)
      return false unless Dir.exists? path
      return false unless File.exists? File.join(path, RELATIVE_INIT_PATH)
      return false unless (EXPECTED_HOME_ENTRIES - Dir.entries(path)).empty?
      true
    end
  end

  Init::add_package_shortcuts
  puts 'Unknown if started from jar (NameError)' if self.running_in_jar?.nil?
  if self.running_in_jar?
    puts "Assuming we are in a jar!"
    require 'rubygems'
    java_import de.recipeminer.environments.FileFinder
    gems_url = FileFinder.new('').getFileOrResource('rubygems')
    Gem::path << gems_url.to_url.to_external_form
    begin
      require 'json'
      puts 'Sucessfully required JSON!'
    rescue NameError
      puts 'Access to gems does not work!'
    end
  else
    self.build_maven_loadpath
    self.build_maven_classpath
    self.set_execution_environment
    require 'ruby-debug'
    if %w{development test}.find (ENV['MINERENV'] || 'development')
      Debugger::settings[:autoeval] = 1
      Debugger::settings[:autolist] = 1
      if (ENV['MINERDEBUG'] && ENV['MINERDEBUG'] != '0') || ($0.end_with? 'rdebug')
        puts "Starting Debugger..."
        Debugger.start
      end
    end
  end
end
